package com.qf.cloud2203.vote.controller;

import cn.hutool.jwt.JWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.cloud2203.domain.constants.Constants;
import com.qf.cloud2203.domain.entity.Vote;
import com.qf.cloud2203.domain.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/vote")
public class VoteController {

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 投票接口
     *
     * @param phone
     * @param cadidateId
     * @param token
     * @return
     * @throws Exception
     */
    @PostMapping("/dovote")
    public ResultVo dovote(String phone, Integer cadidateId, @RequestHeader("token") String token) throws Exception {
        boolean validate = JWT.of(token).setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8)).validate(0);
        if (!validate) {
            throw new Exception("token 无效");
        }
        String tokenRedis = (String) redisTemplate.opsForValue().get(Constants.SECRET + phone);
        if (!token.equals(tokenRedis)) {
            throw new Exception("手机号无效");
        }
        //校验投票时间够不够
        String voteIntervalkey = Constants.VOTE_FIRST_KEY + phone;
        Boolean exist = redisTemplate.hasKey(voteIntervalkey);
        if (exist) {
            throw new Exception("投票间隔不足60秒");
        }
        Vote vote = new Vote();
        vote.setUpdateTime(new Date());
        vote.setCandidateId(cadidateId);
        vote.setPhone(phone);
        //开启redis事务
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.multi();
        try {
            String votelistkey = Constants.VOTE_DETAL_LIST;
            ObjectMapper objectMapper = new ObjectMapper();
            String voteJson = objectMapper.writeValueAsString(vote);
            redisTemplate.opsForList().rightPush(votelistkey, voteJson);
            //把本次投票信息累加到候选人总票数的zset中
            String voteResultKey = Constants.VOTE_RESULT_ZSET;
            redisTemplate.opsForZSet().incrementScore(voteResultKey, cadidateId, 1);
            //2.禁止同一个手机号在接下来的60s内连续投票
            redisTemplate.opsForValue().set(voteIntervalkey, new Date(), 60, TimeUnit.SECONDS);
            //提交事务
            redisTemplate.exec();
            //rabbitTemplate.convertAndSend("vote_exchage", "vote.orange.cat", vote);
        } catch (Exception e) {
            e.printStackTrace();
            //有异常取消事务
            redisTemplate.discard();
        }

        return ResultVo.ok();
    }


}










